package repository

import (
	"dataaysn/internal/model"
	"time"

	"gorm.io/gorm"
)

type HospitalizationDetailRepository interface {
	Create(detail *model.HospitalizationDetail) error
	BatchCreate(details []model.HospitalizationDetail) error
	GetByID(id uint) (*model.HospitalizationDetail, error)
	ListByInpatientNo(inpatientNo string) ([]model.HospitalizationDetail, error)
	ListByHospitalAndDate(hospitalCode string, startDate, endDate time.Time) ([]model.HospitalizationDetail, error)
	DeleteById(id uint) error // 新增删除方法，用于测试用例中模拟数据删除操作，实际项目中可能不需要此方法，因为通常不会直接删除数据，而是通过软删除等方式来标记数据为无效状态。如果需要，可以根据实际情况添加此方法。
	UpdateDetail(detail *model.HospitalizationDetail) error
}

type GormHospitalizationDetailRepository struct {
	db *gorm.DB
}

func NewGormHospitalizationDetailRepository(db *gorm.DB) HospitalizationDetailRepository {
	return &GormHospitalizationDetailRepository{db: db}
}

func (r *GormHospitalizationDetailRepository) Create(detail *model.HospitalizationDetail) error {
	return r.db.Create(detail).Error
}

func (r *GormHospitalizationDetailRepository) BatchCreate(details []model.HospitalizationDetail) error {
	return r.db.CreateInBatches(details, 100).Error
}

func (r *GormHospitalizationDetailRepository) GetByID(id uint) (*model.HospitalizationDetail, error) {
	var detail model.HospitalizationDetail
	err := r.db.First(&detail, id).Error
	return &detail, err
}

func (r *GormHospitalizationDetailRepository) ListByInpatientNo(inpatientNo string) ([]model.HospitalizationDetail, error) {
	var details []model.HospitalizationDetail
	err := r.db.Where("inpatient_no = ?", inpatientNo).Find(&details).Error
	return details, err
}

func (r *GormHospitalizationDetailRepository) ListByHospitalAndDate(hospitalCode string, startDate, endDate time.Time) ([]model.HospitalizationDetail, error) {
	var details []model.HospitalizationDetail
	err := r.db.Where("hospital_code = ? AND bill_date BETWEEN ? AND ?",
		hospitalCode, startDate, endDate).Find(&details).Error
	return details, err
}

func (r *GormHospitalizationDetailRepository) DeleteById(id uint) error {
	return r.db.Delete(&model.HospitalizationDetail{}, id).Error
}

func (r *GormHospitalizationDetailRepository) UpdateDetail(detail *model.HospitalizationDetail) error {
	return r.db.Save(detail).Error
}
